package com.itheima.reggie.filter;
import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(filterName = "LoginCheckFilter",urlPatterns = "/*")
public class LoginCheckFilter implements Filter {
    public static  final AntPathMatcher PATH_MATCHER=new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
      HttpServletRequest Request=(HttpServletRequest) servletRequest;
      HttpServletResponse Response=(HttpServletResponse) servletResponse;

        String requestURI = Request.getRequestURI();

        String [] uris=new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/user/sendMsg",
                "/user/login"
        };
        if (Check(requestURI,uris))
        {
            filterChain.doFilter(Request,Response);
            return;
        }
        if(Request.getSession().getAttribute("employee")!=null)
        {
           Long empId= (Long) Request.getSession().getAttribute("employee");
            BaseContext.setCurrentId(empId);
            filterChain.doFilter(Request,Response);
            return;
        }


        if(Request.getSession().getAttribute("user")!=null)
        {
            Long userId= (Long) Request.getSession().getAttribute("user");
            BaseContext.setCurrentId(userId);
            filterChain.doFilter(Request,Response);
            return;
        }

        Response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));


    }
    public boolean Check(String requestURI,String[] uris)
    {
        for (String uri : uris) {
            boolean match = PATH_MATCHER.match(uri, requestURI);
            if (match){
               return  true;
            }

        }
        return false;
    }
}
